package br.com.californiahotel.client.viewControler;

import br.com.californiahotel.client.CaliforniaHotel;
import br.com.californiahotel.client.CaliforniaHotel.History;
import br.com.californiahotel.client.architecture.viewController.BasicController;
import br.com.californiahotel.client.interfaces.AsyncCallback;
import br.com.californiahotel.client.service.LoginService;
import br.com.californiahotel.client.service.LoginServiceAsync;
import br.com.californiahotel.client.viewControler.LoginView.Field;
import br.com.californiahotel.shared.models.User;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;

public class LoginController extends BasicController {

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);

	public interface Display extends DisplayController {
		DynamicForm getForm();
	}

	public LoginController(Display display) {
		super(display);
	}

	@Override
	public void bind() {
		getDisplay().getForm().getField(Field.OK.getFieldName())
		.addClickHandler(okButtonClick());
		getDisplay().getForm().getField(Field.LOGIN.getFieldName())
		.addKeyPressHandler(fieldKeyPress());
		getDisplay().getForm().getField(Field.PASSWORD.getFieldName())
		.addKeyPressHandler(fieldKeyPress());
	}

	private Display getDisplay() {
		return ((Display)getDisplayController());
	}

	private KeyPressHandler fieldKeyPress() {
		return new KeyPressHandler() {

			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getKeyName().equals("Enter")) {
					getDisplay().getForm()
					.getField(Field.OK.getFieldName())
					.fireEvent(
							new ClickEvent(getDisplay().getForm()
									.getField(Field.OK.getFieldName())
									.getJsObj()));
				}
			}
		};
	}

	private ClickHandler okButtonClick() {
		return new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				loginService.efetuarLogin(
						new User(getDisplay().getForm()
								.getField(Field.LOGIN.getFieldName())
								.getDisplayValue(), getDisplay().getForm()
								.getField(Field.PASSWORD.getFieldName())
								.getDisplayValue()),
								new AsyncCallback<Boolean>() {

							@Override
							public void onSuccess(Boolean result) {
								if (result == true) {
									CaliforniaHotel.changeHistory(History.MAIN);
								} else {
									SC.warn("Login ou Senha incorreto");
								}
							}

						});
			}
		};
	}
}
